<template>
  <el-dialog
    title="关联属性项"
    :visible.sync="_visible"
    width="1000px"
    append-to-body
  >
    <avue-form
      ref="form"
      v-model="form"
      :option="formOption"
    >
      <template #attributeCode>
        <el-select
          v-model="form.attributeCode"
          :disabled="formType==='edit'"
          placeholder="请选择"
        >
          <el-option
            v-for="item in attributeCodeList"
            :key="item.attributeCode"
            :label="item.attributeName"
            :value="item.attributeCode"
          >
          </el-option>
        </el-select>
      </template>
    </avue-form>
    <template #footer>
      <el-button
        type="primary"
        @click="handleUpdate"
      >确定</el-button>
      <el-button @click="_visible=false">取消</el-button>
    </template>
  </el-dialog>
</template>
<script>
import {
  bindPetAttribute,
  editBindPetAttribute,
} from '@/api/core/bindAttribute';
import { formOption } from '@/const/crud/pet/classifyAttributeItem';

export default {
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    attributeCode: {
      // 属性码
      type: String,
    },
    classifyCode: {
      // 品种code
      type: String,
    },
    attributeName: {
      //宠物属性
      type: String,
    },
    attributeCodeList: {
      type: Array,
    },
    formType: {
      type: String,
      default: 'add',
    },
    formData: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      form: {},
      formOption,
    };
  },
  computed: {
    _visible: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit('update:visible', val);
      },
    },
  },
  watch: {
    _visible(val) {
      if (val) {
        this.form.classifyCode = this.classifyCode;
        this.form.attributeName = this.attributeName;
        if (this.formType === 'edit') {
          this.form = this.formData;
        } else {
          this.form.sort = 1;
        }
      } else {
        this.$refs.form.resetFields();
      }
    },
  },
  methods: {
    async handleUpdate() {
      this.form.parentAttributeCode = this.attributeCode;
      const params = {
        ...this.form,
      };
      try {
        console.log(this.formType);
        if (this.formType === 'add') {
          await bindPetAttribute(params);
        } else {
          await editBindPetAttribute(params);
        }
        this.$emit('getRefresh');
        this.$message.success('操作成功！');
        this._visible = false;
      } catch (error) {
        throw new Error(error);
      }
    },
  },
};
</script>
<style lang="scss" scoped>
</style>
